package com.aloda.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.aloda.cache.RedisUtils;
import com.aloda.constant.RedisConstant;
import com.aloda.context.UserBaseContext;
import com.aloda.dto.UserSafetyDTO;
import com.aloda.properties.TokenProperties;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

/**
 * 用户token过期时间刷新拦截器
 */
@Component
public class UserRefreshTokenInterceptor implements HandlerInterceptor {

    @Resource
    private TokenProperties tokenProperties;

    @Resource
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.取出请求头中的token
        String token = request.getHeader(tokenProperties.getUserTokenName());
        if(StrUtil.isBlankIfStr(token)) {
            return true;
        }
        // 2.基于token去redis中寻找用户
        UserSafetyDTO userSafetyDTO = redisUtils.getUserInRedis(token);
        if (BeanUtil.isEmpty(userSafetyDTO)) {
            return true;
        }
        // 3.存在将用户保存
        UserBaseContext.saveUser(userSafetyDTO);
        // 4.刷新redis有效期
        redisUtils.refreshToken(token);
        // 5.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserBaseContext.removeUser();
    }
}
